# 开发时间 2023/6/16 15:14
import tkinter
import tkinter.messagebox

from main.MysqlConnectModule import *
import main.TreeWindows as TreeWindows


def delete_student():
    pass


def update_student():
    pass


def show_student():
    pass


def login(name, pwd, root):
    """

    @param name: 登录用户名
    @param pwd: 登录密码
    @param root: 窗口对象
    @return:
    """
    conn = get_connector()
    cur = get_cur(conn)
    sql = f'select * from t_teacher where username = \'{name}\' and pwd = \'{pwd}\''
    data = get_data(cur, sql)  # data类型为列表，元素为元组
    cur_close(cur)
    conn_close(conn)
    if data:
        # print("success")
        # todo:如果登陆成功，则关闭登录窗口
        root.withdraw()
        TreeWindows.home_window(data[0][3])  # 运行主窗口
    else:
        # print('fail')
        # 如果登陆失败，则弹出失败窗口
        tkinter.messagebox.showerror(title='登录失败', message='账户名或密码错误！')


def register():
    addWindow = tkinter.Tk()
    addWindow.title('注册老师')
    user_label1 = tkinter.Label(addWindow, text='用户名：')
    pwd_label2 = tkinter.Label(addWindow, text='密   码：')
    # sticky='w'，实现两个标签文本左对齐
    user_label1.grid(row=0, column=0, padx=10, pady=5, sticky='w')
    pwd_label2.grid(row=1, column=0, padx=10, pady=5, sticky='w')

    teacher_name = tkinter.Entry(addWindow)
    teacher_pwd = tkinter.Entry(addWindow)
    teacher_name.grid(row=0, column=1, padx=10, pady=5)
    teacher_pwd.grid(row=1, column=1, padx=10, pady=5)
    add_btn = tkinter.Button(addWindow, text='点击注册',
                             command=lambda: add_teacher_to(teacher_name.get(), teacher_pwd.get(), addWindow))
    add_btn.grid(row=2, columnspan=3, padx=5, pady=5)
    addWindow.mainloop()


def add_teacher_to(name, pwd, root):
    """

    @param name: 老师姓名
    @param pwd: 密码
    @param root: 窗口对象
    @return:
    """
    conn = get_connector()
    cur = get_cur(conn)
    sql1 = f'insert into t_teacher values(default,"{name}","{pwd}",1)'
    print("sql1:", sql1)
    if name and pwd:
        try:
            cur.execute(sql1)  # 执行插入的sql语句
            conn.commit()  # 提交到数据库执行
            tkinter.messagebox.showinfo(title='注册成功', message='注册成功！')
            # todo:如果注册成功，则关闭注册窗口
            root.destroy()
        except BaseException:
            conn.rollback()  # 如果发生错误则回滚
            tkinter.messagebox.showerror(title='注册失败！', message='用户名已存在！')
    else:
        tkinter.messagebox.showerror(title='注册失败！', message='内容不能为空！')
    conn_close(conn)
    cur_close(cur)
